﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using UserDefinedForms.Entities;
using UserDefinedForms.Business;

namespace UDFDesign
{
    public partial class DesignableForm : Form
    {
        protected DesignForm designForm;
        protected DesignFormService designFormService = new DesignFormService();
        protected FormControlService controlService = new FormControlService();
        protected ControlListItemService listItemService = new ControlListItemService();

        protected TList<FormControl> listDeletedControl = new TList<FormControl>();

        protected TList<FormControl> listControl = new TList<FormControl>();

        public DesignableForm(DesignForm designForm)
        {
            this.designForm = designForm;

            if (designForm.FormId > 0)
            {
                TList<FormControl> listExistedContrl = controlService.GetByFormId(designForm.FormId);
                listControl.AddRange(listExistedContrl);
            }

            InitializeComponent();
        }

        public DesignableForm()
            : this(new DesignForm())
        {
           
        }

        public void addControl(FormControl control)
        {
            listControl.Add(control);
        }

        public void deleteControl(FormControl control)
        {
            listControl.Remove(control);
            listDeletedControl.Add(control);
        }

        public void save()
        {
            designFormService.Save(designForm);
            foreach (FormControl control in listControl)
            {
                control.FormId = designForm.FormId;
                TList<ControlListItem> listItem = listItemService.GetByControlId(control.ControlId);
                listItemService.Delete(listItem);
                listItemService.Insert(control.ControlListItemCollection);
            }
            controlService.Save(listControl);

            foreach (FormControl delControl in listDeletedControl)
            {
                TList<ControlListItem> listItem = listItemService.GetByControlId(delControl.ControlId);
                listItemService.Delete(listItem);
            }
            controlService.Delete(listDeletedControl);

        }

    }
}
